package com.cate.service.Impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cate.exception.BusinessException;
import com.cate.mapper.UserMapper;
import com.cate.pojo.dto.UserLoginDTO;
import com.cate.pojo.entity.User;
import com.cate.pojo.vo.UserLoginVO;
import com.cate.properties.WeChatProperties;
import com.cate.result.SystemCode;
import com.cate.service.UserService;
import com.cate.utils.HttpClientUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * @CreateTime: 2023/7/31
 * @Author: <==lhd==>
 * @Description:
 */
@Service
@Slf4j
public class UserServiceImpl implements UserService{

    private final String WX_LOGIN_URL = "https://api.weixin.qq.com/sns/jscode2session";

    @Autowired
    private WeChatProperties weChatProperties;

    @Autowired
    private UserMapper userMapper;

    @Override
    public User wxLogin(UserLoginDTO userLoginDTO) {
        // 获得openid
        String openid = getOpenId(userLoginDTO.getCode());

        log.info("威信获得的code{}",userLoginDTO.getCode());

        // 查询数据库是否存在
        User user = userMapper.getByOpenId(openid);
        if(user==null){
            // 添加用户
            user = new User();
            user.setOpenid(openid);
            user.setCreateTime(LocalDateTime.now());
            final int i = userMapper.insert(user);
            if(i<=0){
                log.error("添加用户{}错误",openid);
            }
        }

        return user;
    }


    public String getOpenId(String code){
        Map<String,String> map = new HashMap<>();
        map.put("appid",weChatProperties.getAppid());
        map.put("secret",weChatProperties.getSecret());
        map.put("js_code",code);
        map.put("grant_type","authorization_code");
        final String json = HttpClientUtil.doGet(WX_LOGIN_URL, map);
        log.info("获得微信JSON{}",json);
        JSONObject jsonObject = JSON.parseObject(json);
        final String openid = jsonObject.getString("openid");
        return openid;
    }
}
